package com.t2two.example.projects;

import java.math.BigDecimal;
import java.util.List;

/**
 * @version 1.0
 * @description: TODO
 * @author: lifei
 * @date: 2023/12/4 11:52
 */
public class ExpenseTreeProcessor {
    public static AmountResult calculateExpenses(ExpenseTreeNode node) {
        if (node == null) {
            return new AmountResult(BigDecimal.ZERO, BigDecimal.ZERO);
        }

        List<ExpenseTreeNode> children = node.getChildren();
        if (children != null && !children.isEmpty()) {
            BigDecimal parentAmount = BigDecimal.ZERO;
            BigDecimal selfAmount = node.getExpense();  // 部门自身支出的费用

            for (ExpenseTreeNode child : children) {
                AmountResult childExpenses = calculateExpenses(child);  // 递归计算子部门的支出金额
                parentAmount = parentAmount.add(childExpenses.getParentAmount());  // 累加子部门的支出到父部门
                selfAmount = selfAmount.add(childExpenses.getSelfAmount());
            }

            return new AmountResult(parentAmount.add(selfAmount), selfAmount);
        } else {
            return new AmountResult(node.getExpense(), node.getExpense());
        }
    }
}

